// Copyright (C) 2024 Kumo inc.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
//

#include <kllm/kai/lora.h>

namespace kllm {

    void KaiLora::lora(const KaiRequest &req, KaiResponse&res) const {
        (void)req;
        for (size_t i = 0; i < _context->km_model.loras.size(); ++i) {
            auto & lora = _context->km_model.loras[i];
            LoraInfo info;
            info.set_id(i);
            info.set_path(lora.path);
            info.set_scale(lora.scale);
            *res.mutable_lora_infos()->Add() = info;
        }
    }

    void KaiLora::lora_apply(const KaiRequest &req, KaiResponse&res) {

        int max_idx = _context->km_model.loras.size();

        // clear existing value
        for (auto & lora : _context->km_model.loras) {
            lora.scale = 0.0f;
        }

        // set value
        for (auto entry : req.lora_request().lora_infos()) {
            int id      = entry.id();
            float scale = entry.scale();
            if (0 <= id && id < max_idx) {
                _context->km_model.loras[id].scale = scale;
            } else {
               res.mutable_status()->set_errmsg("invalid adapter id");
                res.mutable_status()->set_code(static_cast<int>(turbo::StatusCode::kInvalidArgument));
                return;
            }
        }
        res.set_model_alias(_context->params.model_alias);
        server_task task;
        task.type = SERVER_TASK_TYPE_SET_LORA;
        const int id_task = _context->queue_tasks.post(task);
        _context->queue_results.add_waiting_task_id(id_task);

        TaskResult result = _context->queue_results.recv(id_task);
        _context->queue_results.remove_waiting_task_id(id_task);
        if(result.error) {
            res.mutable_status()->set_errmsg("unknown error");
            res.mutable_status()->set_code(static_cast<int>(turbo::StatusCode::kUnavailable));
        }
        res.mutable_status()->set_code(static_cast<int>(0));
        res.mutable_status()->set_errmsg("ok");
    }

}  // namespace kllm
